<template>
  <div class="delivery-container">
    <el-card class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="订单号">
          <el-input v-model="listQuery.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="配送状态">
          <el-select v-model="listQuery.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <div class="table-operations">
        <el-button type="primary" @click="handleExport">导出数据</el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="orderNo"
          label="订单号"
          width="180"
        />
        <el-table-column
          prop="customerName"
          label="收货人"
          width="120"
        />
        <el-table-column
          prop="phone"
          label="联系电话"
          width="120"
        />
        <el-table-column
          prop="address"
          label="配送地址"
        />
        <el-table-column
          prop="status"
          label="配送状态"
          width="100"
        >
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter">
              {{ row.status | statusLabelFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="150"
        >
          <template slot-scope="{row}">
            <el-button
              type="text"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleTrack(row)"
            >
              跟踪
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="编辑配送信息" width="500px">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="temp.orderNo" disabled />
        </el-form-item>
        <el-form-item label="收货人" prop="customerName">
          <el-input v-model="temp.customerName" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="配送地址" prop="address">
          <el-input v-model="temp.address" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="配送状态" prop="status">
          <el-select v-model="temp.status">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import Pagination from '@/components/Pagination'

export default {
  name: 'DeliveryManagement',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        pending: 'info',
        delivering: 'warning',
        delivered: 'success',
        failed: 'danger'
      }
      return statusMap[status]
    },
    statusLabelFilter(status) {
      const statusMap = {
        pending: '待配送',
        delivering: '配送中',
        delivered: '已送达',
        failed: '配送失败'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        orderNo: undefined,
        status: undefined
      },
      statusOptions: [
        { label: '待配送', value: 'pending' },
        { label: '配送中', value: 'delivering' },
        { label: '已送达', value: 'delivered' },
        { label: '配送失败', value: 'failed' }
      ],
      temp: {
        orderNo: '',
        customerName: '',
        phone: '',
        address: '',
        status: ''
      },
      dialogVisible: false,
      rules: {
        customerName: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        address: [{ required: true, message: '请输入配送地址', trigger: 'blur' }],
        status: [{ required: true, message: '请选择配送状态', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        // 这里替换为实际的API调用
        const { data, total } = await this.fetchDeliveryList(this.listQuery)
        this.list = data
        this.total = total
      } catch (error) {
        console.error('获取配送列表失败:', error)
        this.$message.error('获取配送列表失败')
      }
      this.listLoading = false
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        page: 1,
        limit: 20,
        orderNo: undefined,
        status: undefined
      }
      this.getList()
    },
    handleEdit(row) {
      this.temp = Object.assign({}, row)
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    async updateData() {
      this.$refs['dataForm'].validate(async valid => {
        if (valid) {
          try {
            // 这里替换为实际的API调用
            await this.updateDelivery(this.temp)
            this.dialogVisible = false
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.getList()
          } catch (error) {
            console.error('更新配送信息失败:', error)
            this.$message.error('更新配送信息失败')
          }
        }
      })
    },
    handleTrack(row) {
      this.$router.push({
        path: `/orders/delivery/track/${row.orderNo}`
      })
    },
    async handleExport() {
      try {
        // 这里替换为实际的API调用
        const data = await this.exportDeliveryData(this.listQuery)
        const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
        saveAs(blob, `delivery-${new Date().getTime()}.xlsx`)
      } catch (error) {
        console.error('导出数据失败:', error)
        this.$message.error('导出数据失败')
      }
    },
    // 模拟API调用
    fetchDeliveryList(params) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve({
            data: [
              {
                orderNo: 'DD20240301001',
                customerName: '张三',
                phone: '13800138000',
                address: '北京市朝阳区xxx街道xxx号',
                status: 'delivering',
                createTime: '2024-03-01 10:00:00'
              }
              // 更多数据...
            ],
            total: 100
          })
        }, 1000)
      })
    },
    updateDelivery(data) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve()
        }, 300)
      })
    },
    exportDeliveryData() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(new Blob(['模拟的Excel数据']))
        }, 300)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.delivery-container {
  padding: 20px;
  
  .filter-container {
    margin-bottom: 20px;
  }
  
  .table-operations {
    margin-bottom: 20px;
  }
}
</style> 